package com.example.com.skills_utf8;

import android.app.Fragment;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import service.IMyComputer;
import service.MyLocalService;
import service.MyRemoteService;


//
public class _67_2Fragment extends Fragment {


    IMyComputer computer;
    ServiceConnection sc;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {


        View view = inflater.inflate(R.layout.fragment_67_2, container, false);


        // 连接服务
        sc = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                computer = IMyComputer.Stub.asInterface(service);

                System.out.println("connected name: "+name);
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                computer = null;
                System.out.println("disconnected name: "+name);
            }
        };

        Button btn_connect = (Button)view.findViewById(R.id.btn_connect);
        btn_connect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // 连接远程服务
                getActivity().bindService(new Intent(getActivity(), MyRemoteService.class), sc, Service.BIND_AUTO_CREATE);

            }
        });


        Button btn_add = (Button)view.findViewById(R.id.btn_add);
        btn_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int result = 0;
                try {
                    result = computer.add(1,2);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                System.out.println("bind result: "+result);
            }
        });


        return view;

    }


    @Override
    public void onDestroy() {
        super.onDestroy();

        getActivity().unbindService(sc);
    }
}
